<?php

class TwigView {
	
	private $_path;
	private $_vars;
	
	private $_twig_loader;
	
	public static $RACINE_PATH;
	public static $TWIG_PATH;
	
	public static $TWIGVIEW_TPL_PATH = "templates/";
	public static $TWIGVIEW_COMPILATION_CACHE = "templates/.twigcache/";
	
	public function __construct($path = "") {
		$default_tpl_path = self::$TWIGVIEW_TPL_PATH;
		$twig_path = self::$TWIG_PATH;
		
		require_once($twig_path.'Autoloader.php');
		Twig_Autoloader::register();
		
		$this->_path = $path;
		$this->_vars = array();
		
		$tpl_paths = array(self::$RACINE_PATH.$default_tpl_path);
		if (realpath(self::$RACINE_PATH) != realpath(".") && file_exists("templates")) {
			$tpl_paths[] = "templates/";
		}
		
		$compilation_cache_path = self::$RACINE_PATH.self::$TWIGVIEW_COMPILATION_CACHE;
		
		if (!file_exists($compilation_cache_path)) {
			mkdir($compilation_cache_path,0777,true);
		}
		
		$this->_twig_loader = new Twig_Loader_Filesystem($tpl_paths);
		$this->_twig_env = new Twig_Environment($this->_twig_loader, array(
		));
		$this->_twig_env->addExtension(new Twig_Extensions_Extension_Text());
		$function = new Twig_SimpleFunction('inputautocomplete', array('TwigView', 'inputautocomplete'));
		$this->_twig_env->addFunction($function);
		$this->detectMobile();
	}
	
	public function detectMobile() {
		require_once(LIB_PATH.'Mobile_Detect-2.5.9/Mobile_Detect.php');
		$detect = new Mobile_Detect();
		$noappredirect = 0;
		if (!empty($_REQUEST['noappredirect']) || !empty($_SESSION['noappredirect'])) {
			$noappredirect = 1;
			$_SESSION['noappredirect'] = true;
		}
		
		$this->assign('ismobile', $detect->isMobile()?'1':'0');
		$this->assign('noappredirect', $noappredirect);
	}
	
	
	public static function inputautocomplete() {
	}
	

	
	public function assign($var, $value) {
		$this->_vars[$var] = $value;
	}
	
	public function render($tpl) {
		$template = $this->_twig_env->loadTemplate($tpl);
		return $template->render($this->_vars);
	}
	
	public function display($tpl, $options = array()) {
		
		$noecho = false;
		if (isset($options['output']) && !$options['output']) {
			$noecho = true;
		}
		
		$view = $this->render($tpl);
		
		if (!$noecho) {
			echo $view;
		}
		return $view;
	}
	
	public function getDisplay($tpl, $options = array()) {
		$options = $options + array(
			'output' => false
		);
		return $this->display($tpl, $options);
	}

}